#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from google.appengine.ext import db
from google.appengine.api import users, urlfetch
from google.appengine.ext import webapp

from StringIO import StringIO
from GPXTimeline import GPXTimeline
from Picasa import Picasa
from mapskey import MAPS_API_KEY
from template import short_header, banner, footer
from Track import getTrack

class Timeline(webapp.RequestHandler):
  def get(self):

    track_key =  self.request.get('key')
    if track_key:
       #track = db.get(db.Key(track_key))
      track = getTrack(track_key)
    else:
       self.redirect('/')
       return
    album_owner = self.request.get('owner')
    if not album_owner:
      album_owner = track.albumOwner
      pass
    album_name = self.request.get('album')
    if  not album_name:
      album_name = track.albumName 
      pass
    album_slip = self.request.get('slip')

    lock = self.request.get('lock')
    if lock != "on":
      lock = "off"
      pass

    try:
      album_slip = int(album_slip)
    except:
      album_slip = 0
      pass

    if track_key:
      track_url = "%s/data?key=%s" % (self.request.host_url, track_key)
      track = db.get(db.Key(track_key))
      track_start = track.getStartDatetimeStr()
      album_start = track_start
      track_name = track.name
      self.kml_url = self.request.host_url + "/download?key=" + track_key
    if album_name:
      album_url = "%s/data?key=%s&owner=%s&album=%s&slip=%d" % (
        self.request.host_url, track_key, album_owner, album_name, album_slip)
      picasa_uri = "http://picasaweb.google.com/data/feed/api/user/%s/album/%s?kind=photo" % (album_owner,album_name)
    else:
      self.redirect('/photos?key=%s' % track_key)
      return
    try:
      urlres = urlfetch.fetch(picasa_uri)
      if urlres.status_code == 200:
        album = urlres.content
        if(album_slip == 0):
          album_start = Picasa(album).getStartDatetimeStr()
          pass
    except:
      # redirect to home  (perhaps with error message)
      pass

    self.response.out.write(short_header(self.request))

    timeline = GPXTimeline().timeline(track.getContent())
    (wpt_a, wpt_b) = timeline[0] 
    self.start_lat = wpt_a.lat
    self.start_lon = wpt_a.lon

#<link rel='stylesheet' href="http://simile.mit.edu/styles/default.css" type="text/css" />
    self.response.out.write("""
<script src="http://simile.mit.edu/timeline/api/timeline-api.js" type="text/javascript"></script>
  <script>
// <[CDATA[
  var tl;
  var bandInfos;

function onLoad(track_url,track_start,album_url,album_start,locked) {
  initialize_map();
  var trackSource = new Timeline.DefaultEventSource();
  var albumSource = new Timeline.DefaultEventSource();
  var theme = Timeline.ClassicTheme.create();
  theme.ether.backgroundColors = ["#CCC","#FDD","#DDF","#CCC"];
  theme.event.highlightColors = ["#FFFF00","#FFFF00","#FFFF00","#FFFF00"];
  theme.event.bubble.height = 200;

  Timeline.DurationEventPainter.prototype._showBubble = function(x, y, evt) {
    link_txt = evt.getLink();
    markerText = evt.getDescription();
    args = link_txt.match(/lat=([-\.\d]*).*lon=([-\.\d]*)/);
    lat = args[1];
    lon = args[2];
    document.getElementById('phlat').innerHTML=lat;
    document.getElementById('phlng').innerHTML=lon;
    document.getElementById('phtit').innerHTML=evt.getText();
    document.getElementById('phtim').innerHTML=evt.getStart();
    document.getElementById('phthum').setAttribute('src', evt.getImage());
    //document.getElementById('phthum').innerHTML=evt.getImage();
    var point = new GLatLng(lat, lon); 
    map.setCenter(point);
    marker.setLatLng( point ); 
    //var marker = new GMarker(point, {draggable: true});
    //map.addOverlay( marker );     
    //alert( args[1] + " " + args[2] );
  }

  bandInfos = [
    Timeline.createBandInfo({
        theme:          theme,
        showEventText:  false,
        trackHeight:    0.3,
        trackGap:       0.0,
        date:           album_start,
        eventSource:    albumSource,
        width:          "10%%", 
        intervalUnit:   Timeline.DateTime.DAY,
        multiple: 1,
        intervalPixels: 300
    }),
    Timeline.createBandInfo({
        theme:          theme,
        trackHeight:    1.0,
        trackGap:       0.0,
        date:           album_start,
        eventSource:    albumSource,
        //showEventText: false,
        width:          "60%%", 
        intervalUnit:   Timeline.DateTime.MINUTE, 
        multiple: 5,
        intervalPixels: 20
    }),
    Timeline.createBandInfo({
        theme:          theme,
        showEventText:  false,
        trackHeight:    0.6,
        trackGap:       0.0,
        date:           track_start,
        eventSource:    trackSource,
        width:          "20%%", 
        intervalUnit:   Timeline.DateTime.MINUTE, 
        multiple: 5,
        intervalPixels: 20

    }),
    Timeline.createBandInfo({
        theme:          theme,
        showEventText:  false,
        trackHeight:    0.3,
        trackGap:       0.1,
        date:           track_start,
        eventSource:    trackSource,
        width:          "10%%", 
        intervalUnit:   Timeline.DateTime.DAY, 
        multiple: 1,
        intervalPixels: 300
    })
  ];
  bandInfos[0].syncWith = 1;
  bandInfos[0].highlight = true;
  bandInfos[3].syncWith = 2;
  bandInfos[3].highlight = true;

  if(locked == "on"){
    bandInfos[2].syncWith = 1;
  }

  tl = Timeline.create(document.getElementById("timeline-tr"), bandInfos, Timeline.HORIZONTAL);

  Timeline.loadXML(track_url, function(xml, url) { 
    trackSource.loadXML(xml, url);
  });
  Timeline.loadXML(album_url, function(xml, url) { 
    albumSource.loadXML(xml, url);
  });
}

function lockBands( lock ){
  if(lock){
   alert("unlock");
  }else{
   alert("unlock?");
  }
}

function checkTime( initial_slip ){
   al_date = tl.getBand(1).getCenterVisibleDate();
   tr_date = tl.getBand(2).getCenterVisibleDate();

   var offset = (tr_date - al_date)/1000;
   if(offset<0)offset=-offset;
   var offset_sec = offset % 60; offset = (offset-offset_sec) / 60;
   var offset_min = offset % 60; offset = (offset-offset_min) / 60;
   var offset_hrs = offset % 24; offset = (offset-offset_hrs) / 24;
   var text = "" + offset + " "
     + offset_hrs + ":" + offset_min + ":" + offset_sec;
   document.getElementById('time-slip').innerHTML=text;
   document.getElementById('slip').setAttribute("value",initial_slip+(tr_date - al_date)/1000);  
}
// ]]>
</script>""")

    self.response.out.write("""<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=%s" type="text/javascript"></script>""" % MAPS_API_KEY)

    self.response.out.write("""</script>
<script type="text/javascript"> 
    //<![CDATA[
    var map;
    var marker;
    var markerText = "<p>hi</p>";
    var geoXml; 
    function kmlLoaded() {
      geoXml.gotoDefaultViewport(map);
    }
    function initialize_map() {
      if (GBrowserIsCompatible()) {
        geoXml = new GGeoXml("%s", kmlLoaded);
        map = new GMap2(document.getElementById("map_canvas")); 
        var center = new GLatLng(%s,%s);
        map.setCenter(center, 11); 
        map.addControl(new GHierarchicalMapTypeControl());
        map.addControl(new GLargeMapControl());
        map.addOverlay(geoXml);
        marker = new GMarker(center, {draggable: true});
        map.addOverlay( marker ); 
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(markerText);
        });
        GEvent.addListener(marker, "dragend", function() {
          posn = marker.getLatLng();
          document.getElementById('phlat').innerHTML=posn.lat();
          document.getElementById('phlng').innerHTML=posn.lng();
        });
      }
    }
 //]]>
</script>""" % (self.kml_url, self.start_lat, self.start_lon))

    self.response.out.write("""</head>""")
 
    self.response.out.write("""<body onload="onLoad('%s','%s', '%s', '%s', '%s');" onresize="onResize();">
""" % (track_url, track_start, album_url, album_start, lock))


    ## Top stripe
    self.response.out.write("""<div  style="width:100%">""")
    self.response.out.write(banner(self.request))
    self.response.out.write("""</div>""")


    #self.response.out.write("""<div style="float: right;">""")
    #self.response.out.write("""<p><b>%s</b></p>""" % track_name)
    #self.response.out.write("""</div>""")

    ## Map stripe
    self.response.out.write("""<div style="height:265px">""")


    ## Info box
    self.response.out.write("""<div style="float:left;width:50%;height:260px;background-color:red;">""")
    self.response.out.write("""<p><img id="phthum"  style="float:right;margin:3px" wsrc="" />
<b><span id="phtit"></span></b><br />
<span id="phtim"></span><br />
<b>latitude</b>&nbsp;<span id="phlat">0N</span><br />
<b>longitude</b>&nbsp;<span id="phlng">0E</span><br />
</p>""")

    self.response.out.write("""
<input type="button" value="Check timeslip" onClick="checkTime(%d);"/>
<span id="time-slip"></span>
<span id="time-tr"></span>""" % album_slip)

    self.response.out.write("""
<form>
<input type="checkbox" name="lock" value="%s" onclick="lockBands(this.checked)"/>
<input type="hidden" name="key" value="%s"/>
<input type="hidden" name="owner" value="%s"/>
<input type="hidden" name="album" value="%s"/>
<input id="slip" type="text" name="slip" value="%d"/>
<input type="submit" value="Fix timeslip"/>
</form>""" % (lock,track_key,album_owner,album_name,album_slip))

    self.response.out.write("""
<form action="/savetimeline" method="get">
<input type="hidden" name="key" value="%s" />
<input type="hidden" name="owner" value="%s" />
<input type="hidden" name="album" value="%s" />
<input type="hidden" name="slip" value="%s" />
<input type="submit" value="Save"/>
</form>"""  %(track_key,album_owner,album_name,album_slip))

    self.response.out.write("""

</div>
""")

    ## Map box

    self.response.out.write("""
    <div id="map_canvas" style="float:left;width:50%;height:260px">
    </div>""")

    self.response.out.write("</div>")


    ## Timeline stripe
    self.response.out.write("""
  <div id="timeline-tr" style="float: left; width: 100%; height: 250px; border: 1px solid #aaa"></div>
""")


    ## Footer stripe

    self.response.out.write("""<div style="width:100%"></div>""")
    self.response.out.write(footer(self.request))
